#!/usr/bin/env python  
# encoding: utf-8   

""" 
@version: v1.0 
@author: null 
@software: PyCharm 
@file: wxmain.py 
@time: 2017.3.24 19:47 
"""

from wxpy import *
from logger_model import Logger
import dbutils

log = Logger('./log/wx_logs.log')

bot = Bot(cache_path=True)

isOpen = True
myInfo = {}
chatList = []
chatedList = []
autoText = '忙'
groupChatList = {}
isOpenGroup = False

tuling = Tuling(api_key='51ee99665b994acdbf86f5cf6b6f2caf')


boring_group = bot.groups().search('测试组')[0]
friends = bot.friends()


@bot.register(friends, msg_types=[TEXT, PICTURE, RECORDING], except_self=False)
def friendsMsg(msg):
    conn, cur = dbutils.connDB()
    log.debug('个人消息---')
    log.info(msg.raw)
    msgText = msg.text
    print(msgText)
    print(myInfo)
    print(msg.sender)
    print(msg.receiver)
    if myInfo == msg.sender == msg.receiver:
        global isOpen
        global isOpenGroup
        if msgText == "//startup":
            isOpen = True
            bot.file_helper.send_msg('机器人已开启')
        if msgText == "//stop":
            isOpen = False
            bot.file_helper.send_msg('机器人已关闭')
        if msgText.find('//[') == 0 and msgText.find(']') == len(msgText) - 1:
            global autoText
            autoText = msgText[3:-1]
            # return '已设置自动回复内容为[ ' + autoText + ' ]'
            bot.file_helper.send_msg('已设置自动回复内容为[ ' + autoText + ' ]')
        if msgText == '//startgroup':
            isOpenGroup = True
            # return '群聊AI开启'
            bot.file_helper.send_msg('群聊AI开启')
        if msgText == '//stopgroup':
            isOpenGroup = False
            # return '群聊AI关闭'
            bot.file_helper.send_msg('群聊AI关闭')

    elif isOpen and myInfo != msg.sender:
        sql = '''insert into wxChatRecord(msgText,msgSender,createTime,msgType,msgRaw) VALUES
            ('{0}','{1}','{2}','{3}',\"{4}\")'''.format(str(msgText), str(msg.sender.name), str(msg.create_time),
                                                        str(msg.type), str(msg.raw).replace('\"', '\''))
        log.debug(sql)
        dbutils.exeSql(conn, cur, sql)
        # print(msg)
        if not msg.sender in chatList:
            if msgText and msgText.find('//openxianliao') != -1:
                chatList.append(msg.sender)
                return '开始陪你唠嗑~输入指令 //closexianliao 关闭闲聊模式'
            elif not msg.sender in chatedList:
                chatedList.append(msg.sender)
                return '我是机器人小弱，老板在' + autoText + '，有事你留言。你还可以输入指令 //openxianliao 进入闲聊模式和我聊天'
        else:
            if msgText and msgText.find('//closexianliao') != -1:
                chatList.remove(msg.sender)
                chatedList.remove(msg.sender)
                return '闲聊模式关闭，输入指令 //openxianliao 再次开启'
            else:
                return tuling.reply_text(msg)
    else:
        sql = '''insert into wxChatRecord(msgText,msgSender,createTime,msgType,msgRaw) VALUES
                    ('{0}','{1}','{2}','{3}',\"{4}\")'''.format(str(msgText), str(msg.sender.name),
                                                                str(msg.create_time), str(msg.type),
                                                                str(msg.raw).replace('\"', '\''))
        log.debug(sql)
        dbutils.exeSql(conn, cur, sql)
    dbutils.connClose(conn=conn, cur=cur)
    pass


@bot.register(boring_group, msg_types=[TEXT, PICTURE, RECORDING, SHARING], except_self=False)
def groupMsg(msg):
    conn, cur = dbutils.connDB()
    log.debug('群消息----------------------')
    log.info(msg.raw)
    print(str(msg))
    if isOpen:
        sql = '''insert into wxChatRecord(msgText,msgSender,createTime,msgType,msgRaw,isGroup,msgMeber) VALUES
              ('{0}','{1}','{2}','{3}',\"{4}\",'1','{5}')'''.format(str(msg.text), str(msg.sender.name),
                                                                    str(msg.create_time), str(msg.type),
                                                                    str(msg.raw).replace('\"', '\''),
                                                                    str(msg.member.name))
        log.debug(sql)
        dbutils.exeSql(conn, cur, sql)
        # print(sql)
        if myInfo != msg.sender:
            if msg.is_at:
                return '我是机器人，BOSS在' + autoText + '，重要事情私聊给我。'
            elif isOpenGroup and myInfo != msg.sender:
                return tuling.reply_text(msg, at_member=False)

    dbutils.connClose(conn=conn, cur=cur)
    pass


if __name__ == "__main__":
    myInfo = bot.friends(update=True)[0]
    chatList.append(bot.file_helper)
    embed()
    pass
